package com.gene.tlonpo.service.remote.server;

import com.gene.tlonpo.exception.TlonpoException;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @author geneX
 * 组件内部通信-server端
 */
@Slf4j
public class TlonpoNettyServer {

    private int port;

    /**
     * channel，启动之后保存
     */
    private Channel channel;

    private EventLoopGroup boss;

    private EventLoopGroup work;

    public TlonpoNettyServer() {
        this.port = 10118;
    }

    public TlonpoNettyServer(int port) {
        this.port = port;
    }

    /**
     * 组件服务端启动
     */
    public void start() {
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup work = new NioEventLoopGroup(32);

        ServerBootstrap bootstrap = new ServerBootstrap();

        try {
            bootstrap.group(boss, work)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childHandler(new TlonpoNettyServerChannelInitializer())
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture future = bootstrap.bind(port).syncUninterruptibly();
            if (future.isSuccess()) {
                this.channel = future.channel();
                this.boss = boss;
                this.work = work;
                log.info("tlonpo server started success");
            }

            //future.channel().closeFuture().syncUninterruptibly();
        } catch (Exception e) {
            log.error("tlonpo server has a unknow error", e);
            throw new TlonpoException("tlonpo server has a unknow error");
        } finally {
//            boss.shutdownGracefully();
//            work.shutdownGracefully();
        }

    }

    public void close() {
        if (channel != null) {
            channel.close();
        }

        if (boss != null) {
            boss.shutdownGracefully();
        }

        if (work != null) {
            work.shutdownGracefully();
        }
    }
}
